package com.sz.controller.frame;

import com.sz.bean.Constants;
import com.sz.bean.Page;
import com.sz.bean.SysiniConfig;
import com.sz.bean.YijiaBeanConfig;
import com.sz.exception.SaveException;
import com.sz.pojo.frame.User;
import com.sz.service.frame.UserService;
import com.sz.util.ToolStr;
import com.sz.util.VerificationCodeUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理
 *
 * @author 哈尼玛
 * @框架文件
 */
@Controller
public class UserController extends BaseController<User> {

    /**
     * 对应pojo的名字
     */
    public static final String POJO_NAME = "user";

    /**
     * 权限url前缀
     */
    public static final String PERMISSION_URL_PREFIX = PERMISSION_PREFIX + POJO_NAME;

    /**
     * 列表
     */
    public static final String LIST_URL = PERMISSION_URL_PREFIX + "/list";
    /**
     * 跳转
     */
    public static final String MODIFY_URL = PERMISSION_URL_PREFIX + "/modify";
    /**
     * 保存
     */
    public static final String SAVE_URL = PERMISSION_URL_PREFIX + "/save";
    /**
     * 设置角色跳转
     */
    public static final String MODIFY_USER_ROLE_URL = PERMISSION_URL_PREFIX + "/modifyUserRole";
    /**
     * 设置角色
     */
    public static final String SAVE_USER_ROLE_URL = PERMISSION_URL_PREFIX + "/saveUserRole";

    //public static final String RESET_PASSWORD_URL = PERMISSION_URL_PREFIX + "/reset";

    /**
     * 跳转修改密码页面
     **/
    public static final String MODIFYPASSWORD_URL = PERMISSION_URL_PREFIX + "/usermodifypassword";
    /**** 修改密码 ***/
    public static final String MODIFY_PASSWORD_URL = PERMISSION_URL_PREFIX + "/modifypasswordfeatures";
    /**
     * 跳转修改个人信息页面
     **/
    public static final String MODIFYMESSAGE_URL = PERMISSION_URL_PREFIX + "/usermodifymessage";
    /**
     * 修改个人信息
     **/
    public static final String MODIFY_MESSAGE_URL = PERMISSION_URL_PREFIX + "/usermodmessage";
    /**
     * 生成二维码
     **/
    public static final String CREATECODE_URL = PERMISSION_URL_PREFIX + "/createcode";
    /**
     * 验证登录
     **/
    public static final String CHECKLOGIN_URL = PERMISSION_URL_PREFIX + "/checkLogin";
    /**
     * 用户退出
     **/
    public static final String EXIT_URL = PERMISSION_URL_PREFIX + "/exit";
    /**
     * 验证二维码
     **/
    public static final String CHECKCODE_URL = PERMISSION_URL_PREFIX + "/checkcode";
    /**
     * 用户登录
     **/
    public static final String LOGIN_URL = PERMISSION_URL_PREFIX + "/login";
    /**
     * 到后台首页
     **/
    public static final String TOMAIN_URL = PERMISSION_URL_PREFIX + "/toMain";
    /**
     * 欢迎界面
     **/
    public static final String TOWELCOME_URL = PERMISSION_URL_PREFIX + "/towelcome";
    /**
     * 删除用户
     **/
    public static final String REMOVE_URL = PERMISSION_URL_PREFIX + "/remove";
    /**
     * 重置密码
     **/
    public static final String RESET_URL = PERMISSION_URL_PREFIX + "/reset";
    /**
     * 更改用户状态
     **/
    public static final String CHANGE_STATUS_URL = PERMISSION_URL_PREFIX + "/changeStatus";

    @Autowired
    private UserService userService;

    public UserController() {
        super(POJO_NAME);
    }

    /**
     * 注销用户
     *
     * @param httpSession, 用来从session中删除当前用户
     */
    @RequestMapping(EXIT_URL)
    public String exit(HttpServletResponse response, Model m, HttpSession httpSession) {
        httpSession.removeAttribute(Constants.SESSION_USER);
        httpSession.removeAttribute(Constants.SESSION_USERNAME);
        return BaseController.LOGIN_PAGE;
    }

    /**
     * 生成二维码
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(CREATECODE_URL)
    public void checkCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("image/jpeg");
        VerificationCodeUtil code = VerificationCodeUtil.Instance();
        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute("code", code.getStr());

        // 禁止图像缓存
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        try {
            transform(code.getImage(), resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 输出图片
     * @param in
     * @param out
     * @throws IOException
     */
    public void transform(InputStream in, OutputStream out) throws IOException {
        int ch = 0;
        try {
            while ((ch = in.read()) != -1) {
                out.write(ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 验证二维码
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(CHECKCODE_URL)
    public String inputVerification(HttpServletRequest req) {
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");
        if (code == null || code.trim().length() <= 0) {
            return ERROR;
        }
        String getcode = req.getParameter("verification");
        if (getcode == null || getcode.trim().length() <= 0) {
            return FAIL;
        }
        if (getcode.trim().length() == 0 || getcode == null) {
            return ERROR;
        } else if (!getcode.toLowerCase().equals(code.toLowerCase())) {
            return FAIL;
        } else {
            return SUCCESS;
        }
    }

    /**
     * 用户登录
     *
     * @param session
     * @param m
     * @param username
     * @param password
     * @param verification 验证码
     * @return
     */
    @RequestMapping(LOGIN_URL)
    public String login(HttpServletResponse response, HttpSession session, Model m, String username, String password,
                        String verification) {
        // 获取当前的Subject
        String code = (String) session.getAttribute("code");
        User user = userService.login(username, password, verification, code);
        System.out.println(user);
        session.setAttribute(Constants.SESSION_USER, user);
        session.setAttribute(Constants.SESSION_USERNAME, user.getUsername());
        return redirectUrl(TOMAIN_URL);
    }

    /**
     * 到后台首页
     *
     * @return
     */
    @RequestMapping(TOMAIN_URL)
    public String toMain(HttpSession session, Model m) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        // 验证是否登录成功
        if (user == null) {
            return LOGIN_PAGE;
        } else {
            String username = user.getUsername();
            if (ToolStr.isEmpty(username)) {
                return LOGIN_PAGE;
            } else {
                user = userService.findByUsername(username);
                if (user == null) {
                    return LOGIN_PAGE;
                } else {
                    return INDEX_PAGE;
                }
            }
        }
    }

    /**
     * 欢迎界面
     */
    @RequestMapping(TOWELCOME_URL)
    public String towelcome() throws Exception {
        return WELCOME_PAGE;
    }

    @Override
    @RequestMapping(MODIFY_URL)
    public String modify(Model m, Long id) {
        m.addAttribute(POJO_NAME, userService.load(id));
        return url(POJO_NAME);
    }

    @RequestMapping(LIST_URL)
    public String list(Model m, Page page, String username, String name) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("username", ToolStr.fuzzy(username));
        params.put("uname", ToolStr.fuzzy(name));
        m.addAttribute("list", userService.find4Page(page, params));
        m.addAttribute("username", username);
        m.addAttribute("name", name);
        return url("list");
    }

    /**
     * 后台新增用户
     *
     * @param user
     * @return
     */
    @Override
    @RequestMapping(SAVE_URL)
    public String save(Model m, User user) {
        userService.save(user);
        return redirectUrl(LIST_URL);
//        return redirectUrl("list");
    }


    /**
     * 删除用户
     */
    @Override
    @RequestMapping(REMOVE_URL)
    public String remove(Model m, String ids) {
        if (ids != null) {
            User user = null;
            for (String didStr : ids.split(",")) {
                long id = ToolStr.sToL(didStr, 0L);
                user = userService.load(id);
                if (user != null) {
                    user.setUserStatus(User.DELETE);
                }
            }
        }
        return redirectUrl(LIST_URL);
//        return redirectUrl("list");
    }

    /**
     * 重置密码 读取配置文件对密码进行重置
     *
     * @param m
     * @return
     */
    @RequestMapping(RESET_URL)
    public String resetPassword(Model m, Long id) {
        String defaultpassword = SysiniConfig.getSysini().getDefault_password();
        User user = userService.load(id);
        user.setPassword(defaultpassword);
        userService.save(user);
        return redirectUrl(LIST_URL);
//        return redirectUrl("list");
    }

    /***** 跳转修改密码页面 ***/
    @RequestMapping(MODIFYPASSWORD_URL)
    public String jumpModifyPassword() {
        return url("modifypassword");
    }

    /**** 接前台数据修改密码 ****/
    @RequestMapping(MODIFY_PASSWORD_URL)
    public String modifyPasswordFeatures(Model m, HttpSession session, String oldpassword, String newpassword) {
        //
        User user = (User) session.getAttribute("sessionUser");
        if (user != null) {
            // String olpassword = Tool.encoderByMd5(oldpassword +
            // user.getPwdSerial());
            String olpassword = ToolStr.encoderByMd5(oldpassword, user.getPwdSerial());
            if (olpassword.equals(user.getPassword())) {
                if (user.getId() >= 0) {
                    user.setPassword(newpassword);
                    userService.save(user);
                    session.removeAttribute("sessionUser");
                    m.addAttribute("success", "success");
                    m.addAttribute("msg", "密码修改成功，请重新登录。");
                    m.addAttribute("url", "/" + YijiaBeanConfig.getBean().getAppName());
                    return MESSAGE_PAGE;
                }
            } else {
                m.addAttribute("msg", "原密码错误，请重新输入。");
                return MESSAGE_PAGE;
            }
        }
        m.addAttribute("msg", "请使用正确的方式操作。");
        return MESSAGE_PAGE;
    }

    /**** 更改用户状态 ****/
    @ResponseBody
    @RequestMapping(CHANGE_STATUS_URL)
    public JSONObject changeStatus(Long uid, Integer status) {
        JSONObject jsonObject = new JSONObject();
        try {
            User user = userService.load(uid);
            user.setUserStatus(status);
            userService.save(user);
            jsonObject.put("success", true);
        } catch (SaveException se) {
            jsonObject.put("success", false);
        }
        return jsonObject;
    }

    /******跳转修改个人信息页面 ***/
    @RequestMapping(MODIFYMESSAGE_URL)
    public String jumpModifyMessage(Long id, Model m, HttpSession session) throws Exception {
        if (id == null) {
            m.addAttribute("user", (User) session.getAttribute("sessionUser"));
        } else
            m.addAttribute("user", userService.get(id));
        return url("modifymessage");
    }

    /**
     * 修改个人信息
     **/
    @RequestMapping(MODIFY_MESSAGE_URL)
    public String modifyUserMessage(Model m, User user, Long id, HttpSession session, String name, String telphone,
                                    String cellphone) {
        userService.save(user);
        m.addAttribute("user", user);
        session.setAttribute("sessionUser", user);
        m.addAttribute("saveSuccess", "ok");
        return url("modifymessage");
    }
}